package com.css.apps.base.user.action;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import com.css.apps.base.common.BaseEnvironment;
import com.css.apps.base.dict.service.DictMan;
import com.css.apps.base.org.model.SOrg;
import com.css.apps.base.user.model.SUser;
import com.css.core.configuration.ConfigurationManager;
import com.css.core.configuration.Environment;
import com.css.core.model.tree.Tree;
import com.css.core.model.tree.TreeCache;
import com.css.core.model.tree.TreeNode;
import com.css.db.query.QueryCache;
import com.css.util.ListUtil;
import com.css.util.StringHelper;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.Action;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author create by Mr.X
 * @Date 2021/8/20- 10:13
 **/
public class ExportRoster extends UserAction {
    private String username;
    private String openFlag;
    private String orgId;
    private String includeFlag = "1";
    private String isBranch = "N";
    private List<String> orgIdList = new ArrayList<String>();

    @Override
    protected String userGo() {
        ServletOutputStream out = null;
        try {
            HttpServletResponse response = resetHttpServletResponse();
            //处理中文请求乱码问题
            this.username = new String(ServletActionContext.getRequest().getParameter("username").getBytes("iso-8859-1"),"utf-8");
            //输出文件到响应
            out = response.getOutputStream();
            EasyExcel.write(out, User.class).sheet("花名册").doWrite(buildData(getIdList()));
            out.flush();
            return Action.SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return Action.ERROR;
        }finally {
            IOUtils.closeQuietly(out);
        }
    }

    //重置请求
    private HttpServletResponse resetHttpServletResponse(){
        HttpServletResponse response = ServletActionContext.getResponse();
        try {
            //设置响应
            response.reset();
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");
            String exportFileName =new String(("花名册.xlsx").getBytes(), "ISO8859-1");
            response.setHeader("Content-Disposition", "filename=" + exportFileName);
            // response.setHeader("Pragma", "No-cache");
            // response.setDateHeader("Expires", 0);
            // response.setContentType("application/octet-stream;charset=UTF-8");
        }catch (Exception e){
            e.printStackTrace();
        }
        return response;
    }

    //构建结果集
    private static List<User> buildData(List<String> idList) {
        List<User> userList =new ArrayList<User>();
        for (String userId : idList) {
            SUser sUser = QueryCache.get(SUser.class,userId);
            User user = new User();
            user.setName(sUser.getRealName());
            user.setSex(DictMan.getDictName("d_sex",sUser.getSex()));
            user.setNation(sUser.getNation());
            userList.add(user);
        }
        return userList;
    }

    /**
     * 使用静态内部类定义花名册导出模板
     */
    @ContentRowHeight(30)
    @HeadRowHeight(30)
    @ColumnWidth(25)
    private static  class User  {
        @ExcelProperty(value = {"姓名"},index = 0)
        private String name;
        @ExcelProperty(value = {"性别"},index = 1)
        private String sex;
        @ExcelProperty(value = {"民族"},index = 2)
        private String nation;
/*
        @ExcelProperty(value = {"花名册","姓名"},index = 0)
        private String name;
        @ExcelProperty(value = {"花名册","性别"},index = 1)
        private String sex;
        @ExcelProperty(value = {"花名册","民族"},index = 2)
        private String nation;
*/

        // private String uuid;
        // private String realName;
        // private String loginName;
        // private String orgId;
        // private String orgName;
        //
        // //新增业务字段 Mr.X
        // private String sex;                 //性别
        // private Date birthday;  			//生日
        // private String idcard;	  			//身份证号
        // private String contactor;  			//联系人
        // private String contactphone;  		//联系方式
        // private String nativeplace;  		//籍贯
        // private String birthplace;  		//出生地
        // private String liveplace;  			//成长地
        // private String nation;  			//民族
        // private String health;  			//健康状况
        // private Date joinworktime;  		//加入工作时间
        // private Date joinpartytime;  		//入党时间
        // private String political_landscape; //政治面貌
        // private String joinpartycode;		//入党时间文字
        // private String secondparty;  		//第二党派
        // private String thirdparty;	 		//第三党派
        // private String manage_state; 		//人员管理状态
        // private String person_type;  		//人员类别
        // private String manager_type; 		//管理类别
        // private String skill;        		// 熟悉专业有何特长
        // private String remark;              //备注
        // private String professiontech_duty; //专业技术职务
        // private String resume;				// 简历
        // private String current_duty;		//现任职务
        // private String reward_and_punish;	//奖惩综述
        // private String examine_conclusion;  //年度考核结果
        // private String full_time_education; //学历、学位(全日制)
        // private String full_time_school_major;//毕业院校即专业（全日制）
        // private String on_the_job_education; //学历、学位(在职)
        // private String on_the_job_school_major;//毕业院校即专业（在职）


        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }

        public String getNation() {
            return nation;
        }

        public void setNation(String nation) {
            this.nation = nation;
        }
    }

    private static  String checknull(String field){
        return StringHelper.isEmpty(field) ? "" : field.trim();
    }

    //获取当前查询页的全部用户Id
    private List<String> getIdList(){
        Map paramMap = obtainOrgIdMap();
        this.orgId = (String) paramMap.get("curOrgId");
        orgIdList = (List<String>) paramMap.get("childOrgIdWithSelf");
        QueryCache qc = new QueryCache("select a.uuid from SUser a " + getWhere() + " order by a.orderNum,a.lastmodifytime");
        setWhere(qc);
        return qc.list();
    }

    private Map<String,Object> obtainOrgIdMap(){
        Map<String,Object> map = new HashMap();
        Tree tree = new TreeCache(SOrg.class);
        TreeNode curNode = StringHelper.isNotEmpty(orgId) ?
                tree.getTreeNode(orgId) : ("Y".equalsIgnoreCase(isBranch) ? tree.getTreeNode(sUser.getOrganId()) : tree.getRoot().get(0));
        map.put("curOrgId",curNode.getNodeId());
        if("1".equals(includeFlag)){
            //点击当前组织情况，注入当前节点的ID
            orgIdList.add(curNode.getNodeId());
        }else{
            //点击包含下级情况,注入当前节点ID和全部子节点ID
            orgIdList.add(curNode.getNodeId());
            for (TreeNode node : curNode.getAllChildren()) {
                orgIdList.add(node.getNodeId());
            }
        }
        map.put("childOrgIdWithSelf",orgIdList);
        return map;
    }

    public String getWhere() {
        StringBuffer sb = new StringBuffer(" where a.delFlag='" + Environment.UN_DELETE_STATE + "'");
        if (ListUtil.isLstNotEmpty(orgIdList)) {
            sb.append(" and exists(select 1 from SUserOrg uo where uo.userId=a.uuid and  uo.deptId in(:orgIdList) ) ");
        }
        // run模式下只能显示普通用户
        if (!ConfigurationManager.isAdminMode()) {
            sb.append(" and a.userType = '" + BaseEnvironment.USERTYPE_NORMAL + "' ");
        }
        if (StringHelper.isNotEmpty(openFlag))
            sb.append(" and a.openFlag = :openFlag ");
        if (StringHelper.isNotEmpty(username))
            sb.append(" and (a.loginName like :name or a.realName like :name) ");
        return sb.toString();
    }

    public void setWhere(QueryCache qc) {
        if (ListUtil.isLstNotEmpty(orgIdList)) {
            qc.setParameter("orgIdList", orgIdList);
        }
        if (StringHelper.isNotEmpty(username))
            qc.setParameter("name", "%" + username.trim() + "%");
        if (StringHelper.isNotEmpty(openFlag))
            qc.setParameter("openFlag", openFlag.trim());
    }

    private static String ListToStr(List<String> list) {
        String str = "";
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                str += "'" + list.get(i) + (i != list.size() - 1 ? "'," : "'");
            }
        }
        return str;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getOpenFlag() {
        return openFlag;
    }

    public void setOpenFlag(String openFlag) {
        this.openFlag = openFlag;
    }

    public String getOrgId() {
        return orgId;
    }

    public void setOrgId(String orgId) {
        this.orgId = orgId;
    }

    public String getIncludeFlag() {
        return includeFlag;
    }

    public void setIncludeFlag(String includeFlag) {
        this.includeFlag = includeFlag;
    }

    public String getIsBranch() {
        return isBranch;
    }

    public void setIsBranch(String isBranch) {
        this.isBranch = isBranch;
    }

    public List<String> getOrgIdList() {
        return orgIdList;
    }

    public void setOrgIdList(List<String> orgIdList) {
        this.orgIdList = orgIdList;
    }
}
